题解 P1972 [SDOI2009]HH的项链

题意概括:给定一个长度为$N$的自然数序列$(N\leqslant500000$,数的范围$0$到$1000000$之间的整数),有$M$个询问,每个询问两个整数$l,r$表示$l$~$r$区间内有几个不同的数$(M\leqslant500000)$

这道题我们考虑离线+树状数组。

设$last_{i}$表示$1$~当前枚举到的右端点 这个序列中i这个数最后出现的位置,如果要求$l$~$r$之间不同的数个数,只要求有几个$last_{i}$在$l$~$r$之间即可,因为我们可以将当前不为空的$last_{i}$分成两类,一类为大小在$1$~$(l-1)$中,因为$last_{i}$表示最后出现的位置,所以在$l$之后不可能有$i$这个数,我们将这一类数设为$a$;另一类为大小在$l$~$r$中,由于$last_{i}$的定义,所以$i$这个数一定在$l$~$r$之间,我们将这一类数设为$b$。显然答案就是$b$,所以我们只需要求$sum_{r}-sum_{l-1}$即可(因为$sum_{r}=a+b,sum_{l-1}=a)$。

我们将询问保存下来,设为$b$数组,将$b$数组按照右端点排序,从让$i=1$~$n$枚举右端点,若$i=b[j].r$,则$j++$并统计答案,然后更新$last$数组。

单点修改,区间查询,显然可以用树状数组维护。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <bits/stdc++.h>
#define ll long long
struct node{
int l,r,num;
}b[3000000];
using namespace std;
inline int read(){
int s=0,w=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
return s*w;
}
int ans[3000000],a[3000000],n,m,last[3000000],c[3000000];
inline int lowbit(int x){
return x&(-x);
}
inline void change(int x,int d){
if (!x)return;
for (;x<=n;x+=lowbit(x))
c[x]+=d;
}
inline int query(int x){
int res=0;
for (;x;x-=lowbit(x))
res+=c[x];
return res;
}
inline bool cmp(node a,node b){
return a.r<b.r;
}
int main(){
n=read();
for (int i=1;i<=n;i++)
a[i]=read();
m=read();
for (int i=1;i<=m;i++)
b[i].l=read(),b[i].r=read(),b[i].num=i;
sort(b+1,b+1+m,cmp);
int t=1;
for (int i=1;i<=n;i++){
change(i,1);
change(last[a[i]],-1);
while (b[t].r==i){
ans[b[t].num]=query(b[t].r)-query(b[t].l-1);
t++;
}
last[a[i]]=i;
}
for (int i=1;i<=m;i++)
printf("%d\n",ans[i]);
}